package org.dragon.services.impls;

import jakarta.annotation.Resource;
import org.dragon.commons.Const;
import org.dragon.commons.Times;
import org.dragon.mappers.AccountExtendMapper;
import org.dragon.mappers.RoleExtendMapper;
import org.dragon.models.Account;
import org.dragon.models.RedisSessionRole;
import org.dragon.models.Role;
import org.dragon.services.AccountService;
import org.dragon.services.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/18 11:26
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountExtendMapper accountExtendMapper;

    @Resource
    private RoleService roleService;

    @Override
    public Account findById(String id) {
        return StringUtils.hasText(id) ? accountExtendMapper.selectByPrimaryKey(id) : null;
    }

    @Override
    public Account findByEmail(String email) {
        return StringUtils.hasText(email) ? accountExtendMapper.findByEmail(email) : null;
    }

    @Override
    public List<RedisSessionRole> findRoles(String accountId) {
        List<Role> roles = roleService.findRoles(accountId);
        List<RedisSessionRole> result = new ArrayList<>();

        for (Role role : roles) {
            RedisSessionRole r = new RedisSessionRole();
            r.role = role;
            r.permissions = roleService.findPermissions(role.getId());
            result.add(r);
        }

        return result;
    }

    @Override
    public void save(Account account) {
        if (account != null) {
            if (account.getId() == null) {
                account.setId(Const.ulid());
                account.setCreateTime(Times.now());
                accountExtendMapper.insert(account);
            } else {
                accountExtendMapper.updateByPrimaryKey(account);
            }
        }
    }
}
